<template>
  <!-- 会员列表 -->
  <div class="mod-user page-user-list">
    <div class="search-bar">
      <!-- native modifier has been removed, please confirm whether the function has been affected  -->
      <el-form
        ref="searchFormRef"
        :inline="true"
        class="search-form"
        :model="searchForm"
        @submit.prevent
      >
        <div class="input-row">
          <el-form-item
            prop="memberName"
            :label="$t('users.name') + ':'"
          >
            <el-input
              v-model="searchForm.memberName"
              type="text"
              clearable
              :placeholder="$t('users.name')"
            />
          </el-form-item>
          <el-form-item
            prop="userMobile"
            :label="$t('publics.mobilePhone') + ':'"
          >
            <el-input
              v-model="searchForm.userMobile"
              type="text"
              clearable
              :placeholder="$t('publics.mobilePhone')"
            />
          </el-form-item>
          <el-form-item
            prop="status"
            :label="$t('publics.status') + ':'"
          >
            <el-select
              v-model="searchForm.status"
              clearable
              :placeholder="$t('publics.status')"
            >
              <el-option
                v-for="item in status"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <!-- 会员标签 -->
          <el-form-item
            :label="$t('user.userTag')+':'"
            prop="userTag"
          >
            <el-select
              v-model="searchForm.userTag"
              v-el-select-loadmore="loadmore"
              value-key="userTagId"
              multiple
              clearable
              collapse-tags
              :placeholder="$t('user.userTagDefaultTxt')"
            >
              <el-option
                v-for="item in tagList"
                :key="item.userTagId"
                :label="item.tagName"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <div
              class="default-btn primary-btn"
              @click="onSearch(true)"
            >
              {{ $t('crud.searchBtn') }}
            </div>
            <div
              class="default-btn"
              @click="resetForm()"
            >
              {{ $t('user.reset') }}
            </div>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <div class="main-container">
      <div class="operation-bar">
        <div
          v-if="isAuth('user:userList:updateGrowth')"
          class="default-btn"
          :class="{'disabled-btn': dataListSelections.length <= 0}"
          @click="updateGrowth()"
        >
          {{ $t('user.updateGrowth') }}
        </div>
        <div
          v-if="isAuth('brand:coupon:send')"
          class="default-btn"
          :class="{'disabled-btn': dataListSelections.length <= 0}"
          @click="updateCoupon()"
        >
          {{ $t('user.sendCoupons') }}
        </div>
        <div
          v-if="isAuth('user:userList:addLabel')"
          class="default-btn"
          :class="{'disabled-btn': dataListSelections.length <= 0}"
          @click="updateTags()"
        >
          {{ $t('user.tagging') }}
        </div>
        <div
          v-if="isAuth('user:userList:importUser')"
          class="primary-btn default-btn"
          :disabled="importDisabled"
          @click="importUser()"
        >
          {{ $t('user.userImport') }}
        </div>
        <div
          v-if="isAuth('user:userList:exportUser')"
          class="primary-btn default-btn"
          :disabled="exportDisabled"
          @click="exportUser()"
        >
          {{ $t('user.export') }}
        </div>
      </div>
      <div class="table-con">
        <div
          v-if="dataList.length === 0"
          class="empty-text"
        >
          {{ $t('user.noData') }}
        </div>
        <el-table
          :data="dataList"
          header-cell-class-name="table-header"
          row-class-name="table-row-low"
          style="width: 100%"
          @selection-change="selectionChange"
        >
          <el-table-column
            fixed
            type="selection"
            align="center"
            width="60"
          />
          <el-table-column
            fixed
            :label="$t('users.name')"
            prop="nickName"
            align="center"
            width="120"
          />
          <el-table-column
            fixed
            prop="pic"
            align="center"
            :label="$t('publics.profilePicture')"
          >
            <template #default="scope">
              <div class="table-cell-image">
                <img
                  v-if="!scope.row.pic"
                  src="@/assets/img/userImg.jpg"
                  style="width: 130px;"
                  alt
                >
                <img
                  v-else
                  :src="checkFileUrl(scope.row.pic)"
                  alt
                >
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="userMobile"
            width="120"
            align="center"
            :label="$t('publics.mobilePhone')"
          />
          <el-table-column
            prop="levelName"
            width="120"
            align="center"
            :label="$t('user.regularMembershipLevel')"
          >
            <template #default="scope">
              <span v-if="scope.row.shopLevelType === 0">
                {{ scope.row.shopLevelName }}
              </span>
              <span v-else>
                --
              </span>
            </template>
          </el-table-column>
          <el-table-column
            prop="growth"
            width="120"
            align="center"
            :label="$t('user.growth')"
          />
          <el-table-column
            prop="status"
            width="120"
            align="center"
            :label="$t('publics.status')"
          >
            <template #default="scope">
              <span>{{ [$t('publics.disable'),$t('publics.normal')][scope.row.status] }}</span>
            </template>
          </el-table-column>
          <el-table-column
            width="120"
            align="center"
            prop="consAmount"
            :label="$t('user.consumptionAmount')"
          />
          <el-table-column
            width="120"
            align="center"
            prop="actualAmount"
            :label="$t('user.actuallypaid')"
          />
          <el-table-column
            width="120"
            align="center"
            prop="consTimes"
            :label="$t('user.consumptionTimes')"
          />
          <el-table-column
            width="120"
            align="center"
            prop="averDiscount"
            :label="$t('user.averageDiscount')"
          />
          <el-table-column
            width="120"
            align="center"
            prop="afterSaleAmount"
            :label="$t('order.refundAmount')"
          />
          <el-table-column
            width="120"
            align="center"
            prop="afterSaleTimes"
            :label="$t('user.refundTimes')"
          />
          <el-table-column
            v-if="isAuth('user:userList:edit')"
            fixed="right"
            align="center"
            :label="$t('crud.menu')"
            width="230"
          >
            <template #default="scope">
              <div class="text-btn-con">
                <div
                  class="text-btn default-btn"
                  @click.stop="onAddOrUpdate(scope.row.userId)"
                >
                  {{ $t('user.edit') }}
                </div>
              </div>
            </template>
          </el-table-column>
          <template #empty>
            <div>
              &nbsp;
            </div>
          </template>
        </el-table>
      </div>
      <el-pagination
        :current-page="page.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="page.pageSize"
        :total="page.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="onPageSizeChange"
        @current-change="onPageChange"
      />
    </div>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update
      v-if="addOrUpdateVisible"
      ref="addOrUpdateRef"
      @refresh-data-list="refreshChange"
    />
    <update-user-growth
      v-if="updateGrowthVisible"
      ref="updateGrowthRef"
      @refresh-data-list="refreshChange"
    />
    <update-user-tags
      v-if="updateTagsVisible"
      ref="updateTagsRef"
      :tag-category="1"
      :type="1"
      @refresh-data-list="refreshChange"
    />
    <update-user-coupon
      v-if="updateCouponVisible"
      ref="updateCouponRef"
      :get-way="1"
      @refresh-data-list="refreshChange"
    />
    <excel-user-import
      v-if="importUserVisible"
      ref="importUserRef"
      :type="1"
      @refresh-data-list="refreshChange"
    />
  </div>
</template>

<script setup>
import AddOrUpdate from './add-or-update.vue'
import UpdateUserTags from './components/update-user-tags/index.vue'
import UpdateUserCoupon from './components/update-user-coupon/index.vue'
import UpdateUserGrowth from './components/update-user-growth/index.vue'
import ExcelUserImport from './components/excel-user-import/index.vue'
import { ElLoading } from 'element-plus'
import { isAuth, checkFileUrl } from '@/utils/index.js'

const vElSelectLoadmore = {
  onMounted: (el, binding) => {
    // 获取element-ui定义好的scroll盒子
    const SELECTWRAP_DOM = el.querySelector('.el-select-dropdown .el-select-dropdown__wrap')
    SELECTWRAP_DOM.addEventListener('scroll', function () {
      /**
       * scrollHeight 获取元素内容高度(只读)
       * scrollTop 获取或者设置元素的偏移值,常用于, 计算滚动条的位置, 当一个元素的容器没有产生垂直方向的滚动条, 那它的scrollTop的值默认为0.
       * clientHeight 读取元素的可见高度(只读)
       * 如果元素滚动到底, 下面等式返回true, 没有则返回false:
       * ele.scrollHeight - ele.scrollTop === ele.clientHeight;
       */
      const condition = SELECTWRAP_DOM.scrollHeight - SELECTWRAP_DOM.scrollTop <= (SELECTWRAP_DOM.clientHeight + 0.5)
      if (condition) {
        binding.value()
      }
    })
  }
}

let tempSearchForm = null // 保存上次点击查询的请求条件

const importDisabled = ref(false)
const page = reactive({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
})
const searchForm = reactive({
  userTag: [],
  memberName: '',
  userMobile: '',
  levelType: '',
  // 会员等级
  level: '',
  status: null,
  userRegStartTime: null, // 注册起始时间
  userRegEndTime: null // 注册结束时间
})
const levelTypes = [
  {
    label: $t('user.ordinaryMember'),
    value: 0,
    children: []
  }, {
    label: $t('user.paidMembership'),
    value: 1,
    children: []
  }
]

const status = [
  {
    label: $t('publics.disable'),
    value: 0
  }, {
    label: $t('publics.normal'),
    value: 1
  }
]
const tagSearchParam = {
  size: 10,
  current: 1
}
onMounted(() => {
  getMemberLevelList()
  getDataList(page)
  getMemberTags()
})

/**
 * 获取会员等级列表
 */
const getMemberLevelList = () => {
  for (let index = 0; index < 2; index++) {
    http({
      url: http.adornUrl('/user/userLevel/list'),
      method: 'get',
      params: http.adornParams({
        userLevelType: index
      })
    }).then(({ data }) => {
      const children = []
      if (data) {
        data.forEach(el => {
          children.push({
            value: el.level,
            label: el.levelName
          })
        })
      }
      levelTypes[index].children = children
    })
  }
}

const dataList = ref([])
// 获取数据列表  /admin/user/page
const getDataList = (pageParam, newData = false) => {
  if (newData || !tempSearchForm) {
    tempSearchForm = JSON.parse(JSON.stringify(searchForm))
  }
  tempSearchForm.userTag = null
  http({
    url: http.adornUrl('/user/user/pageUser'),
    method: 'get',
    params: http.adornParams(
      Object.assign(
        {
          current: pageParam == null ? page.currentPage : pageParam.currentPage,
          size: pageParam == null ? page.pageSize : pageParam.pageSize
        },
        tempSearchForm
      )
    )
  }).then(({ data }) => {
    dataList.value = data.records
    page.total = data.total
  })
}

const addOrUpdateVisible = ref(false)
const addOrUpdateRef = ref(null)
// 新增 / 修改
const onAddOrUpdate = (id) => {
  addOrUpdateVisible.value = true
  nextTick(() => {
    addOrUpdateRef.value?.init(id, 1)
  })
}

// 条件查询 JSON.stringify(arr)
const onSearch = (newData = false) => {
  let arr = ''
  if (searchForm.userTag.length !== 0) {
    searchForm.userTag.forEach(item => {
      arr = arr + item.userTagId + ','
    })
  }
  searchForm.tagIds = arr
  page.currentPage = 1
  getDataList(page, newData)
}

// 刷新回调用
const refreshChange = () => {
  getDataList(page)
}

const onPageSizeChange = (val) => {
  page.pageSize = val
  getDataList(page)
}

const onPageChange = (val) => {
  page.currentPage = val
  getDataList(page)
}

const searchFormRef = ref(null)
const resetForm = () => {
  searchFormRef.value.resetFields()
  searchForm.userTag = []
  searchForm.userRegStartTime = null
  searchForm.userRegEndTime = null
}

const dataListSelections = ref([])
// 多选变化
const selectionChange = (val) => {
  dataListSelections.value = val
}

const updateGrowthVisible = ref(false)
const updateGrowthRef = ref(null)
// 修改成长值
const updateGrowth = (id) => {
  if (dataListSelections.value.length <= 0) {
    return
  }
  const ids = id ? [id] : dataListSelections.value.map(item => {
    return item.userId
  })
  updateGrowthVisible.value = true
  nextTick(() => {
    updateGrowthRef.value?.init(ids)
  })
}

const updateTagsVisible = ref(false)
const updateTagsRef = ref(null)
const updateTags = (id) => {
  if (dataListSelections.value.length <= 0) {
    return
  }
  const ids = id ? [id] : dataListSelections.value.map(item => {
    return item.userId
  })
  updateTagsVisible.value = true
  nextTick(() => {
    updateTagsRef.value?.init(ids)
  })
}

const updateCouponVisible = ref(false)
const updateCouponRef = ref(null)
const updateCoupon = (id) => {
  if (dataListSelections.value.length <= 0) {
    return
  }
  const ids = id ? [id] : dataListSelections.value.map(item => {
    return item.userId
  })
  updateCouponVisible.value = true
  nextTick(() => {
    updateCouponRef.value?.init(ids)
  })
}

const importUserVisible = ref(false)
const importUserRef = ref(null)
/**
 * 导入用户
 */
const importUser = () => {
  importUserVisible.value = true
  nextTick(() => {
    importUserRef.value?.init()
  })
}

const exportDisabled = ref(false)
/**
 * 导出单品
 */
const exportUser = () => {
  exportDisabled.value = true
  const loading = ElLoading.service({
    lock: true,
    target: '.table-con',
    customClass: 'export-load',
    background: 'transparent',
    text: $t('formData.exportIng')
  })
  http({
    url: http.adornUrl('/user/user/exportUser'),
    method: 'get',
    params: http.adornParams(searchForm),
    responseType: 'blob' // 解决文件下载乱码问题
  }).then(({ data }) => {
    loading.close()
    exportDisabled.value = false
    const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })
    const fileName = $t('user.userInformationForm')
    const elink = document.createElement('a')
    if ('download' in elink) { // 非IE下载
      elink.download = fileName
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      URL.revokeObjectURL(elink.href) // 释放URL 对象
      document.body.removeChild(elink)
    } else { // IE10+下载
      navigator.msSaveBlob(blob, fileName)
    }
  }).catch(() => {
    loading.close()
  })
}

let tagTotal = 0
// 会员标签列表
const tagList = ref([])
/**
 * 获取会员标签列表
 */
const getMemberTags = () => {
  http({
    url: http.adornUrl('/user/userTag/byTagType'),
    method: 'get',
    params: http.adornParams(
      tagSearchParam
    )
  }).then(({ data }) => {
    if (!data) return
    tagTotal = data.total
    tagList.value = [...tagList.value, ...data.records]
  })
}
const loadmore = () => {
  tagSearchParam.current++
  if (tagList.value.length < tagTotal) {
    getMemberTags()
  }
}

</script>

<style lang="scss" scoped>
@use "index";
</style>
